package server;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Set;

import client.link.util.ByteConvert;
import client.serial.MethodCallEntity;

import com.google.gson.Gson;

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(21111,2, InetAddress.getByName("127.0.0.1"));
        Gson gson = new Gson();
        while(true){
            Socket socket = server.accept();
            InputStream input = socket.getInputStream();
            byte[] head = new byte[4];
            input.read(head);
            int length = ByteConvert.byte2Int(head);
            byte[] content = new byte[length];
            input.read(content);
            String con = new String(content,"utf-8");
            MethodCallEntity request = gson.fromJson(con, MethodCallEntity.class);
            //get interface to find impl 
            //set to var impl
            Class impl = Class.forName("service.impl.InfoServiceImpl");
            Object o = impl.newInstance();
            Set<String> argTypes =  request.getArgList().keySet();
            
            Class[] mArgs = new Class[argTypes.size()]; 
            
            int index = 0;
            for (String clazz : argTypes) {
                mArgs[index++] = Class.forName(clazz);
            }
            
            Method method = impl.getMethod(request.getMethodName(), mArgs);
            System.out.println(method.invoke(o, request.getArgList().values().toArray()));
                    
        }
    }
}
